import time
from playwright.sync_api import sync_playwright
import os
import shutil

from seldom.project_temp.confrun_web import timeout


class BrowserAutomation:
    def __init__(self, browser_type='chromium'):
        self.browser_type = browser_type
        self.browser = None
        self.page = None
        self.playwright = None

    def start_browser(self, headless=True):
        self.playwright = sync_playwright().start()
        if self.browser_type == 'chromium':
            self.browser = self.playwright.chromium.launch(headless=headless, args=['--start-maximized'], slow_mo=2000)
            # self.browser.new_page(no_viewport=True)
        elif self.browser_type == 'firefox':
            self.browser = self.playwright.firefox.launch(headless=headless)
        elif self.browser_type == 'webkit':
            self.browser = self.playwright.webkit.launch(headless=headless)
        else:
            raise ValueError(f"Unsupported browser type: {self.browser_type}")

    def new_page(self):
        if not self.browser:
            raise RuntimeError("Browser is not started. Call start_browser() first.")
        self.page = self.browser.new_page()

    def close_browser(self):
        if self.browser:
            self.browser.close()
        if self.playwright:
            self.playwright.stop()

    def goto(self, url):
        if not self.page:
            raise RuntimeError("No page is open. Call new_page() first.")
        self.page.goto(url)

    def click(self, selector):
        if not self.page:
            raise RuntimeError("No page is open. Call new_page() first.")
        self.page.click(selector)

    def fill(self, selector, text):
        if not self.page:
            raise RuntimeError("No page is open. Call new_page() first.")
        self.page.fill(selector, text)

    def wait_for_selector(self, selector, options):
        if not self.page:
            raise RuntimeError("No page is open. Call new_page() first.")
        self.page.wait_for_selector(selector, options)

    # 获取文本
    def get_text(self, selector):
        if not self.page:
            raise RuntimeError("No page is open. Call new_page() first.")
        return self.page.inner_text(selector)

    # 截屏
    def take_screenshot(self, path):
        if not self.page:
            raise RuntimeError("No page is open. Call new_page() first.")
        self.page.screenshot(path=path)

    # 获取当前时间
    def get_now_time(self):
        """
        返回当前时间
        :return: 返回当前时间，格式：%Y%m%d_%H%M%S
        """
        now_time = time.strftime("%Y%m%d_%H%M%S", time.localtime())
        return now_time

    # 删除results下除了history的所有文件
    def get_rm(self):
        # 设置你想删除文件的文件夹路径
        folder_path = '../results'
        # 获取文件夹内容
        contents = os.listdir(folder_path)
        # 遍历文件夹内容
        for item in contents:
            item_path = os.path.join(folder_path, item)
            if item == 'history':  # 如果是'history'文件夹或文件，跳过
                continue
            elif os.path.isdir(item_path):  # 如果是文件夹，删除文件夹及其所有内容
                shutil.rmtree(item_path)
            else:  # 如果是文件，删除文件
                os.remove(item_path)


# 示例用法
if __name__ == "__main__":
    automation = BrowserAutomation(browser_type='chromium')
    automation.start_browser(headless=False)
    automation.new_page()
    # automation.goto("https://www.baidu.com")
    # automation.close_browser()
    # automation.get_now_time()
    # BrowserAutomation().get_rm()
